<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useSysStore } from "stores/sysStore";
import { TypeRTCConfig, Wss } from "src/utils/type";
import VideoCallIng from "pages/videoCallIng.vue";
import eventBus from "src/utils/eventBus";
import { useQuasar } from "quasar";
import { userBehavior, loginOut, formatDate } from "src/utils/util";
import APIClient from "src/utils/APIClient";
let sysStores = useSysStore();
let $q = useQuasar();

let isElectron = ref(window.ipcChannel)

let workState = ref({
  online: false,
  leave: false
})

let callState = ref('standby'); //  calling-->群众正在呼叫  serviceIng-->正在接待群众
let workStateDict: any = {
  online_status: () => workState.value.online = true,
  offline_status: () => workState.value.online = false,
  leave_line_status: () => workState.value.leave = true,
  back_line_status: () => workState.value.leave = false,
}

watch(() => sysStores.wssMessage, (newVal) => {
  console.log('接受消息', newVal)
  let msg: Wss = (newVal as Wss);
  //控制工作人员在线/不在线/离开/回来的状态
  if (workStateDict[msg.message_type])
    return workStateDict[msg.message_type]();
  //获取在线用户的情况
  if (msg.message_type == 'online_users') return getOnlineUser(msg)
  //-----------------以上操作无需检验状态，以下的操作需要在线 如果不在线或在离开状态，一律return-----------------
  if (!workState.value.online || workState.value.leave) return;
  //被呼叫的时候触发
  if (msg.message_type == 'request_connect') return onCall(msg);
  //如果坐席处于被呼叫状态，且接收了呼叫
  if (msg.message_type == 'invite_connection_resp') return startService(msg);
}, {
  deep: true,
})

watch(() => callState.value, (val) => {
  if (val == 'serviceIng') clearInterval(pendulum);
  else setPendulum();
})

onMounted(() => {
  // 工作人员登录后进入页面默认发起一次在线情况的获取
  sysStores.sendWss({ message_type: 'get_online_users' })
  setPendulum();
  getDate();
  normalMatter()
})

//坐席角色要定时检查群众呼叫的队列，如果存在则修改为calling状态，通知坐席去接待
let pendulum: number = 0;
const setPendulum = () => {
  clearInterval(pendulum);
  if (sysStores.userInfo.role_id != 4) return; //只有坐席需要定时检查是否有群众在排队呼叫
  pendulum = setInterval(() => {
    sysStores.sendWss({
      message_type: 'get_online_users',
    })
  }, 10000)
}

let pageDate = ref('');
const getDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  pageDate.value = `${year}年${month.toString().padStart(2, '0')}月`;
}

//向服务发送invite_connection，表示获取一个群众连线
const inviteConnection = () => {
  if (sysStores.userInfo.role_id == 5)
    return callState.value = 'serviceIng'; //部门直接进入
  sysStores.sendWss({ message_type: 'invite_connection' });
  // window.ipcDirect && window.ipcDirect.openNewWin();

}

//坐席人员被呼叫的时候执行该函数
const onCall = (msg: Wss) => {
  callState.value = 'calling'
  window.ipcChannel && ipcChannel.notify();
}

//wss返回invite_connection_resp，并携带频道信息等，此时通知群众进入频道开始视频
const startService = (msg: Wss) => {
  if (sysStores.userInfo.role_id == 5)
    return departmentStartService();//部门需要点击同意
  callState.value = 'serviceIng';
  sysStores.crowdId = msg.message.src_id;
  window.ipcChannel && ipcChannel.maxWin();
}

const departmentStartService = () => {
  callState.value = 'calling';
  window.ipcChannel && ipcChannel.notify();
}

//工作人员点击上岗 line控制在岗状态  leave控制离开状态
const workStateChange = (line: string) => {
  if (line == 'line') sysStores.sendWss({ message_type: workState.value.online ? 'offline' : 'online' })
  if (line == 'leave') sysStores.sendWss({ message_type: workState.value.leave ? 'back_line' : 'leave_line' })
}


//获取在线的用户列表 | 两秒获取一次在线用户信息 | 若有群众在呼叫状态需要接听
let customers = ref([]);
let customersLine = ref(0);
let masters = ref([]);
const getOnlineUser = (msg: any) => {
  customers.value = msg.message?.customers || [];
  masters.value = msg.message?.masters;
  customersLine.value = msg.message?.customers?.filter(x => { return x.is_online }).length;

  //如果不是standby状态 | 如果没有等待的群众 | 如果工作人员的状态不在线或者是离开 | 如果不是坐席
  if (callState.value != 'standby') return
  if (!customersLine.value) return;
  if (!workState.value.online || workState.value.leave) return
  if (sysStores.userInfo.role_id != 4) return;

  //以上都排除时候才是被呼叫状态
  callState.value = 'calling'
}


//videoCalling中出发离开的时候，页面需要回到操作台
eventBus.$on('leaveChannel', async () => {
  callState.value = 'standby';
  userBehavior({
    operation_type_id: 'exit_channel',
    operation_content: '离开频道'
  })
  sysStores.RTCConfig = {} as TypeRTCConfig;
})

const openAgent = () => {
  userBehavior({ operation_type_id: 'view_agent' }) //用户行为统计,查看监控
  window.open('https://deyang.flopsai.cn')
}
const openMonitor = () => {
  userBehavior({ operation_type_id: 'view_monitoring' }) //用户行为统计,查看监控
  window.open('https://console.shengwang.cn/overview')
}

// 获取常办事项
const matterList = ref([])
const normalMatter = () => {
  APIClient.get('/query/faq').then(res => {
    matterList.value = res?.data
  })
}

const evaluationPoint = ref(5)
</script>

<template>
  <!--  <voice-to-text></voice-to-text>-->
  <VideoCallIng :key="Math.random()" v-if="callState == 'serviceIng'" role="crowd"></VideoCallIng>
  <div class="worker-box" v-else>
    <div class="work-top" :class="{ 'work-top-mr': isElectron }">
      <div class="btn" @click="workStateChange('line')">
        <svg class="icon" aria-hidden="true">
          <use :xlink:href="workState.online ? '#icon-a-mianzaigangrenyuan' : '#icon-tianjiarenyuan'"></use>
        </svg>
        <span class="text">{{ workState.online ? '离岗' : '上岗' }}</span>
      </div>
      <div class="btn" @click="workStateChange('leave')" v-show="workState.online">
        <svg class="icon" aria-hidden="true">
          <use :xlink:href="workState.leave ? '#icon-back' : '#icon-zanshilikai'"></use>
        </svg>
        <span class="text">{{ workState.leave ? '返回' : '离开' }}</span>
      </div>
      <div class="btn" @click="openAgent">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-wenda"></use>
        </svg>
        <span class="text">问答</span>
      </div>
      <div class="btn" @click="loginOut">
        <img class="btn-img" src="../../assets/images/index/loginout.png">
        <span class="text">退出</span>
      </div>
    </div>
    <div class="worker-con">
      <div class="work-status" v-show="!workState.online">
        您现是登录未上岗状态，不能接受群众视频连线。
        <br>上岗前请确保发型整洁、着装规范、妆容得体，展现专业服务的第一印象与职业态度。
      </div>
      <div class="work-status" v-show="workState.online && !workState.leave">
        您已上岗，注意接听群众视频连线。
      </div>
      <div class="work-status" v-show="workState.leave">
        您现是暂时离开状态，不能接受群众视频连线。
      </div>

      <div class="work-data">
        <div class="work-info">
          <div class="eva-box">
            <div class="tit">您的动态服务星级</div>
            <q-rating v-model="evaluationPoint" :max="5" size="2.5em" color="#F4EA2A" icon="star_border"
              icon-selected="star" />
          </div>
          <div class="info-one">今日接待<span class="strong">1</span>次
          </div>
          <div class="info-one">本周接待<span class="strong">8</span>次
          </div>
          <div class="info-one">本月累计接待<span class="strong">19</span>次
          </div>
          <br>
          <div class="info-one">本周平均接待时长<span class="strong">28</span>分钟
          </div>
          <div class="info-one">本月平均接待时长<span class="strong">29</span>分钟
          </div>
          <br>
          <div class="info-one">
            群众对你的服务评价最多的是：
            <br>耐心，解决问题认真快速
          </div>
        </div>
        <div class="work-line">
          <div class="line-tit">
            <span>后台支撑坐席在线情况</span>
          </div>
          <div class="work-crowd" v-for="x in masters">
            <div class="user">{{ x.department_short_name }}</div>
            <div class="des">
              <div class="d1">{{ x.name }}</div>
              <div class="d2">{{ x.department_name }}</div>
            </div>
          </div>
        </div>

        <div class="work-line">
          <div class="line-tit">
            <span>常办事项</span>
          </div>
          <div class="work-crowd" v-for="x in matterList">
            <div class="des">
              <div class="d1">{{ x.FrequentlyAskedQuestions }}</div>
              <div class="d2">
                <span class="depart">{{ x.Department }}</span>
                <span>{{ formatDate(x.CreatedAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="work-log" v-show="callState == 'calling'">
      <div class="call-ing">
        <span class="c1">来自群众PC的呼叫...</span>
        <img class="c2" src="../../assets/images/call.png" alt="" @click="inviteConnection">
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.worker-box {
  user-select: none;
  width: 100%;
  height: 100%;

  .work-top {
    position: fixed;
    right: 10px;
    top: 0;
    height: 60px;
    line-height: 60px;
    padding: 0 10px;
    display: flex;
    justify-content: end;
    align-items: center;
    width: 300px;

    .line-up {
      font-size: 20px;
      font-weight: 500;
      color: #8B2CF3;
    }

    .btn {
      position: relative;
      width: 35px;
      height: 35px;
      background-image: linear-gradient(-225deg, #679EF1 0%, #B587CF 48%, #9781EE 100%);
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      border-radius: 10px;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white !important;
      margin-left: 20px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 8px 32px rgba(68, 129, 235, 0.1);
      overflow: hidden;

      .btn-img {
        width: 22px;
        height: 22px;
      }

      &:hover {
        transform: translateY(-2px);
        background-image: linear-gradient(-225deg, #679EF1 0%, #B587CF 48%, #9781EE 100%);
        box-shadow: 0 12px 40px rgba(68, 129, 235, 0.2);

        .icon {
          transform: translateY(-8px) scale(0.8);
        }
        .btn-img {
          transform: translateY(-6px) scale(0.7);
        }

        .text {
          opacity: 1;
          transform: translateY(0);
        }
      }

      .icon,.btn-img {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        font-size: 15px;
      }

      .text {
        position: absolute;
        bottom: 3px;
        font-size: 10px;
        line-height: 12px;
        font-weight: 500;
        white-space: nowrap;
        opacity: 0;
        transform: translateY(10px);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        pointer-events: none;
      }
    }
  }

  .work-top-mr {
    right: 180px !important;
  }

  .worker-con {
    min-width: 1100px;
    min-height: 700px;
    background: #F2F2F2;

    .work-status {
      color: #333;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      height: 100px;
      padding: 20px 100px;
    }

    .work-data {
      display: flex;
      align-items: center;
      justify-content: center;
      height: calc(100vh - 220px);

      .work-info {
        height: 400px;
        margin-right: 20px;
        color: #666;
        font-size: 13px;
        line-height: 22px;
        padding: 15px 20px;

        .eva-box {
          margin-bottom: 20px;

          .tit {
            color: #333;
            text-align: center;
            margin-bottom: 8px;
          }
        }

        .info-one {
          width: 185px;

          .strong {
            color: #FFC000;
            font-size: 14px;
          }
        }
      }
    }

    .work-line {
      position: relative;
      width: 300px;
      height: 400px;
      border: 1px solid #E7E6E6;
      background: #E7E6E6;
      border-radius: 20px;
      padding: 15px 20px;
      margin-right: 15px;
      overflow-y: auto;

      .line-tit {
        font-size: 14px;
        padding-bottom: 10px;
        display: flex;
        align-items: center;
        color: #333;

        span {
          margin-right: 10px;
        }
      }

      // 隐藏滚动条
      &::-webkit-scrollbar {
        display: none;
      }

      -ms-overflow-style: none;
      scrollbar-width: none;


      .work-crowd {
        display: flex;
        margin-bottom: 8px;
        justify-content: start;
        align-items: center;
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 10px;
        padding: 5px 8px;
        width: 260px;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.15);
          transform: translateX(-5px);
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }

        .user {
          width: 35px;
          height: 35px;
          border-radius: 35px;
          text-align: center;
          line-height: 35px;
          background-color: blue;
          font-size: 13px;
          color: white;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        }

        .des {
          width: 100%;
          padding-left: 10px;

          .d1 {
            font-size: 13px;
            font-weight: 500;
            color: #444;
          }

          .d2 {
            width: 100%;
            font-size: 10px;
            color: #666;
            display: flex;
            justify-content: space-between;

            .depart {
              font-size: 12px;
              color: #333;
            }
          }
        }
      }
    }


  }

  .work-log {
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.7);
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;

    .call-ing {
      display: flex;
      justify-content: start;
      padding-top: 20px;
      padding-bottom: 20px;
      align-items: center;

      .c1 {
        font-size: 24px;
        color: #f2f2f2;
      }

      .c2 {
        width: 60px;
        margin-left: 20px;
        height: 60px;
        animation: incoming-call 1.6s infinite;
        cursor: pointer;
        transition: all .3s ease-in-out;
      }

      .c2:hover {
        transition: all .3s ease-in-out;
        transform: scale(1.3);
      }
    }

    @keyframes incoming-call {
      0% {
        transform: translateX(0);
      }

      50% {
        transform: translateX(0);
      }

      52% {
        transform: translateX(-5px);
      }

      54% {
        transform: translateX(5px);
      }

      56% {
        transform: translateX(-5px);
      }

      58% {
        transform: translateX(5px);
      }

      60% {
        transform: translateX(-5px);
      }

      62% {
        transform: translateX(5px);
      }

      64% {
        transform: translateX(-5px);
      }

      66% {
        transform: translateX(5px);
      }

      68% {
        transform: translateX(-5px);
      }

      70% {
        transform: translateX(5px);
      }

      72% {
        transform: translateX(-5px);
      }

      74% {
        transform: translateX(5px);
      }

      76% {
        transform: translateX(-5px);
      }

      78% {
        transform: translateX(5px);
      }

      80% {
        transform: translateX(-5px);
      }

      82% {
        transform: translateX(5px);
      }

      84% {
        transform: translateX(-5px);
      }

      86% {
        transform: translateX(5px);
      }

      88% {
        transform: translateX(-5px);
      }

      90% {
        transform: translateX(5px);
      }

      92% {
        transform: translateX(-5px);
      }

      94% {
        transform: translateX(5px);
      }

      96% {
        transform: translateX(-5px);
      }

      98% {
        transform: translateX(5px);
      }

      100% {
        transform: translateX(0);
      }
    }

    .call-log {
      margin-top: 10px;
      padding: 5px 0;
      color: grey;
      font-size: 16px;
      cursor: pointer;

      span {
        margin-right: 10px;
      }
    }

    .call-log:hover {
      color: #1976D2;
    }
  }
}
</style>
